using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//当一个物体B在物体A前方45度角度范围内，并且离A只有5米距离时，在控制台打印”发现入侵者”.
public class Lesson2_exercise : MonoBehaviour
{
    public Transform player;
    //攻击距离
    public float distance = 5;
    //扇形角度
    public float angle = 45;
    public int segments = 20;   // 扇形细分段数（越高越平滑）

    void DrawAtkArea()
    {
        //绘制攻击区域
        Vector3 center = transform.position;
        Vector3 forward = transform.forward;
        // 绘制扇形的两条边
        Debug.DrawRay(center, forward * distance, Color.red);
        Debug.DrawRay(center, Quaternion.Euler(0, angle / 2, 0) * forward * distance, Color.red);
        Debug.DrawRay(center, Quaternion.Euler(0, -angle / 2, 0) * forward * distance, Color.red);

        // 绘制扇形的弧线
        Vector3 prevPoint = forward * distance;
        for (int i = 1; i <= segments; i++)
        {
            float t = (float)i / segments;
            float currentAngle = Mathf.Lerp(-angle / 2, angle / 2, t);
            Vector3 nextPoint = Quaternion.Euler(0, currentAngle, 0) * forward * distance;
            Debug.DrawLine(center + prevPoint, center + nextPoint, Color.red);
            prevPoint = nextPoint;
        }
    }
    void Update()
    {
        Debug.DrawRay(transform.position, player.position - transform.position, Color.red);
        float distance = Vector3.Distance(this.transform.position, player.position);
        if (distance < this.distance)
        {
            float angle = Vector3.Angle(this.transform.forward, player.position - this.transform.position);
            if (angle < this.angle / 2)
            {
                Debug.LogFormat("发现入侵者(distance:{0} angle:{1})", distance, angle);
            }
        }
        DrawAtkArea();
    }
}
